﻿
package extremefx.ui {
	import extremefx.IDisposable;
	import extremefx.events.MouseEventArgs;
	import extremefx.ui.styles.UIStates;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;		

	/**
	 * @author Marcelo Volmaro
	 */
	public final class BitmapButton implements IDisposable {

		private var _holder:Sprite;
		private var _button:ButtonSprite;
		private var _disposing:Boolean;
		private var _oldState:uint;
		private var _background:Bitmap;
		private var _bitmaps:Vector.<BitmapData>;

		public function BitmapButton(pNormal:BitmapData, pHover:BitmapData = null, pActive:BitmapData = null) {
			_bitmaps = Vector.<BitmapData>([pNormal, pHover, pActive]);
			
			_holder = new Sprite();
			_button = new ButtonSprite(_holder);
			
			_button.onRollOver.add(_rollOver);
			_button.onRollOut.add(_rollOut);
			_button.onReleaseOutside.add(_rollOut);
			_button.onDragOut.add(_rollOut);
			_button.onPress.add(_press);
			_button.onDragOver.add(_press);
			
			_button.onRelease.add(_release);

			_setView(UIStates.NORMAL);
			
			_button.enabled = true;
		}
		
		private function _rollOut(pSender:ButtonSprite, pArgs:MouseEventArgs):void{
			_setView(UIStates.NORMAL);
		}
		
		private function _rollOver(pSender:ButtonSprite, pArgs:MouseEventArgs):void{
			_setView(UIStates.HOVER);
		}
		
		private function _press(pSender:ButtonSprite, pArgs:MouseEventArgs):void{
			_setView(UIStates.ACTIVE);
		}
		
		private function _release(pSender:ButtonSprite, pArgs:MouseEventArgs):void{
			_setView(UIStates.NORMAL);
		}
		
		private function _setView(pState:uint):void{
			if (_oldState == pState) return;
			_oldState = pState;
			
			var bmpData:BitmapData;
			if (_bitmaps.length < pState) pState = _bitmaps.length;
			while ((bmpData = _bitmaps[--pState]) == null && pState != 0);

			if (_background){
				_holder.removeChild(_background);
			}
			
			if (bmpData != null){
				_background = _holder.addChildAt(new Bitmap(bmpData), 0) as Bitmap;
			}
		}
		
		public function dispose():void {
			if (_disposing) return;
			_button.dispose();
			if (_holder && _holder.parent) _holder.parent.removeChild(_holder);
		}
		
		public function get view():Sprite {
			return _holder;
		}
		
		public function get button():ButtonSprite {
			return _button;
		}
	}
}
